import { defineStore } from 'pinia'
import edit from "wangeditor";
import Cookies from 'js-cookie'
import { UserEntity } from '@/store/interface'
import {nextTick} from 'vue'
import {Whoami} from '@/api/user'
import {SignIn, UserAuth,SignOut} from '@/api/auth'
// import {SignOut} from '@/api/user'
import {CreateKnot} from '@/api/knot'

import { User} from "@/types/proto/api/v1/user_service";
import {getWssUrl} from "@/config"
import { UserUnit, P2PExchangeRecord, ExchangeReocrdUnit } from '@/types/proto/api/v1/exchange_service';
import { CreateKnotRequest, Knot, CreateKnotChatRequest } from '@/types/proto/api/v1/knot_service';
import { Phase,Exchange } from '@/types/proto/api/v1/chat_service';

import { Metadata } from 'nice-grpc-web';
import { InteractType, TopicUnit } from '@/types/proto/common/common';
import { WebSocketClient} from "@/utils/websocket";

interface UserStoreActions {
  signIn: (username: string, password: string, tenantname: string, neverExpire?: boolean) => Promise<any>;
  singout: () => void;
  getUserInfo: () => Promise<any>;
  // setToken:(data: any) => void;
  getHeaderToken:()=>Metadata;
  // playMusic:() =>void;
  // toBottom:()=>void;
  // changeReaded:(id: number)=>void;
  // initEditor:()=>void;
}

export const useUserStore = defineStore<'user', UserEntity, {}, UserStoreActions>("user", {
  state: (): UserEntity => {
    return {
      token: Cookies.get('Authorization'),
      tenant:"",
      tenantUrn:"",
      userInfo: null,
      drawer: false,
      recipient: null,
      readyRecipient: null,
      navId: '2',
      sessionList: [],
      sessionSelectId: 0,
      allSessionList: [],
      allSessionSelectId: 0,
      navList: [
        { index: '1', lable: "消息列表", icon: "i-ep-chat-dot-round" },
        { index: '2', lable: "用户列表", icon: "i-ep-user" },
      ],
      exchanges: [],
      sendInfo: null,
      chatScrollbar: null,
      chatEditor: null,
      editor: null,
      editorData: '',
      openMusic: false,
      onlineStatus:false,
      tipMusic: null,
      subject:null,
      assistant:null,
      topic:null,
      granary:null
    }
  },
  
  persist: {
    // 存储到 localStorage
    key: 'user-store',
    storage: localStorage,
    
   // 指定要持久化的状态
    pick: ['token', 'userInfo', 'sessionList', 'exchanges','tenantUrn','tenant'],
    
    // 可以在恢复时进行数据转换
    afterHydrate: (context:any) => {
      console.log('store data restored')
    }
  },

  actions: {
    // setToken(data: any){
    //   Cookies.set('Authorization', data?.token)
    //   this.token = data?.token
    // },

    getHeaderToken() {
      const metadata = new Metadata();
      metadata.set('authorization', this.token||"");  // 添加认证头
      return metadata
    },

    getUserInfo(){
      return new Promise((resolve, reject)=>{
        Whoami().then((res: User) => {
          this.userInfo = res
          resolve('获取成功')
        }).catch(()=>{
          reject()
        })
      })
    },

    signIn(username: string, password: string,  tenantname:string = "", neverExpire: boolean = false) {
      console.log("sigin test, usename:", username)
      return new Promise((resolve, reject)=>{
        SignIn({username: username, password: password,neverExpire: neverExpire, tenantName: tenantname}).then((res: UserAuth) => {
          console.log("sigin res:",res)
          this.userInfo = res.user
          this.token = res.token
          this.tenant = res.user.tenantName
          this.tenantUrn = res.user.tenantUrn
          console.log(res)
          resolve('登录成功')
        }).catch((e:any)=>{
          reject(e||'登录失败')
        })
      })
    },

    // 声音提示
    // playMusic() {
    //   if (this.tipMusic != null && this.openMusic) {
    //     this.tipMusic.currentTime = 0
    //     this.tipMusic.play()
    //   }
    // },
    // 设置会话窗口到达底部
    // toBottom() {
    //   const timer = setTimeout(()=>{
    //     this.chatScrollbar?.setScrollTop(9999)
    //     clearTimeout(timer)
    //   },300)
    // },
    // 修改信息已读状态
    // changeReaded(id: number) {
    // },
    // 初始化编辑器
    // initEditor() {
    //   if (this.editor != null) {
    //     this.editor.destroy();
    //     this.editor = null;
    //   }
    //   this.editor = new edit("#chatEditor")
    //   this.editor.config.showFullScreen = false
    //   this.editor.config.focus = true

    //   // 自定义菜单栏
    //   this.editor.config.menus = []

    //   // change
    //   this.editor.config.onchange = (html: any) => {
    //     this.editorData = html
    //   };

    //   // 上传最多1张
    //   this.editor.config.uploadImgMaxLength = 1
    //   // 添加上传本地图片接口
    //   this.editor.config.customUploadImg = function (
    //     files: any,
    //     insert: Function
    //   ) {
    //     insert(files)
    //   };
    //   // 聚焦操作
    //   nextTick(()=>{
    //     this.editor.create()
    //     this.editor.txt.html(this.editorData)
    //   })
    // },
    // 注销
    singout() {
      SignOut({}).then(() => {
        console.log('注销成功')
      }).catch((err) => {
        console.log(err)
      })
      Cookies.remove('Authorization')
      this.$patch((state)=>{
        state.userInfo = null
        state.token = undefined
        state.sessionList = []
        state.sessionSelectId=0
        state.allSessionList = []
        state.allSessionSelectId = 0
      })
    },
  }
})